/*
 * @(#)MaintContactPersonAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.contact.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.contact.ContactErrorConstant;
import com.dcivision.contact.bean.ContactList;
import com.dcivision.contact.bean.ContactPerson;
import com.dcivision.contact.dao.ContactPersonDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintContactPersonAction.java

  This class is for maint contact person.

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   05/01/2005
    @version         $Revision: 1.12 $
*/

public class MaintContactPersonAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.12 $";

  public MaintContactPersonAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.contact.dao.ContactPersonDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.CONTACT_PERSON);
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintContactPersonForm maintForm = (MaintContactPersonForm)form;

    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    log.debug( ((maintForm!=null) ? maintForm.getClass().getName() : "")+", OP Mode:"+opMode+", Nav Mode:"+navMode);

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    try {
      if (!Utility.isEmpty(opMode)) {
        if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
          // Insert operation.
          try {
            this.insertRecord(mapping, maintForm, request, response);
            this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
            this.commit(request);
            addMessage(request, MESSAGE_RECORD_INSERT);
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            if(ContactPerson.NAV_MODE_NEW_CONTACTS.equals(navMode)){
              maintForm.setNavMode(navMode);
              return mapping.findForward(navMode);   
            }else{
              maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
            }
          } else {
            if(ContactPerson.NAV_MODE_NEW_CONTACTS.equals(navMode)){
              maintForm.setNavMode(ContactPerson.NAV_MODE_VIEW_CONTACTS);
              return mapping.findForward(ContactPerson.NAV_MODE_VIEW_CONTACTS);   
            }else{
              maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
              return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
            }
          }
        } else if (GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode)) {
          // Insert and New operation.
          try {
            this.insertRecord(mapping, maintForm, request, response);
            this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
            this.commit(request);
            form.reset(mapping, request);
            this.init(mapping, maintForm, request, response);
            addMessage(request, MESSAGE_RECORD_INSERT);
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            if(ContactPerson.NAV_MODE_NEW_CONTACTS.equals(navMode)){
              maintForm.setNavMode(navMode);
              return mapping.findForward(navMode);   
            }else{
              maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
            }
          } else {
            if(ContactPerson.NAV_MODE_NEW_CONTACTS.equals(navMode)){
              maintForm.setNavMode(ContactPerson.NAV_MODE_NEW_CONTACTS);
              return mapping.findForward(ContactPerson.NAV_MODE_NEW_CONTACTS);   
            }else{
              maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
            }
          }
        }else{
          return super.execute(mapping,form,request,response);
        }
      }else{
        if(ContactPerson.NAV_MODE_NEW_CONTACTS.equals(navMode)){
          return mapping.findForward(navMode);   
        }else{
          return super.execute(mapping,form,request,response);   
        }
      }
    } catch (ApplicationException ex) {
      handleApplicationException(request, ex);
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    }
  }
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactPersonForm maintForm=(MaintContactPersonForm)form;
    ContactPersonDAObject contactPersonDAO=new ContactPersonDAObject(sessionContainer,conn);
    maintForm.setOwnerID(sessionContainer.getUserRecordID().toString());    
    ContactPerson contactPerson=new ContactPerson();
    if(checkDuplicatedContactPerson(request,maintForm)){
      throw new ApplicationException(ContactErrorConstant.DUPLICATE_CONTACT_PERSON);    
    }else{
      contactPerson=(ContactPerson)contactPersonDAO.insertObject(maintForm.getFormData());
    }
    maintForm.setFormData(contactPerson);
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	SessionContainer sessionContainer=this.getSessionContainer(request);
  	MaintContactPersonForm maintForm=(MaintContactPersonForm)form;
    if(ContactList.SHARING_TYPE_PRI.equals(maintForm.getPublicFlag()) && !(maintForm.getOwnerID().equals(sessionContainer.getUserRecordID().toString()))){
      throw new ApplicationException(ContactErrorConstant.CONTACT_NO_PERMISSION);     
    }else{
      if(checkDuplicatedContactPerson(request,maintForm)){
        throw new ApplicationException(ContactErrorConstant.DUPLICATE_CONTACT_PERSON);
      }else{
        super.updateRecord(mapping,form,request,response);
      }
    }
  }
  
  /**
   * check duplicated contact person.
   * @param request
   * @param firstName
   * @param lastName
   * @param email
   * @return boolean
   * @throws ApplicationException
   */
  protected boolean checkDuplicatedContactPerson(HttpServletRequest request,MaintContactPersonForm maintForm) throws ApplicationException{
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    ContactPersonDAObject contactPersonDAO=new ContactPersonDAObject(sessionContainer,conn);
    List contactPersonList=contactPersonDAO.getListByFirstNameLastNameEmail(maintForm.getFirstName(),maintForm.getLastName(),maintForm.getEmail(),maintForm.getPublicFlag());
    if(Utility.isEmpty(maintForm.getID())){
      if(contactPersonList.size()>0){
        return true;
      }
    }else{
      for(int i=0;i<contactPersonList.size();i++){
        ContactPerson contactPerson=(ContactPerson)contactPersonList.get(i);
        if(!contactPerson.getID().toString().equals(maintForm.getID())){
          return true;
        }
      }
    }
    return false;
  }

}